<template>
  <div class="major-expense-management">
    <h2 class="title">重大开销事项管理</h2>
    <div class="toolbar">
      <el-input
          v-model="searchQuery"
          placeholder="搜索开销名称"
          style="width: 200px; margin-right: 10px;"
          @input="fetchExpenses"
      />
      <el-button type="primary" @click="openAddDialog">添加开销</el-button>
    </div>
    <el-table :data="expenses" style="width: 100%">
      <el-table-column prop="expenseName" label="开销名称"></el-table-column>
      <el-table-column prop="totalAmount" label="总金额"></el-table-column>
      <el-table-column prop="amountUnit" label="金额单位"></el-table-column>
      <el-table-column prop="createdAt" label="创建时间" :formatter="formatDate"></el-table-column>
      <el-table-column prop="updatedAt" label="修改时间" :formatter="formatDate"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="editExpense(scope.row.id)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteExpense(scope.row.id)">删除</el-button>
          <el-button size="mini" @click="showDetails(scope.row.id)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page.sync="page"
        @current-change="fetchExpenses"
    ></el-pagination>

    <!-- 添加/编辑开销对话框 -->
    <el-dialog :visible.sync="dialogVisible" title="添加/编辑开销" width="50%" @close="handleDialogClose">
      <el-form :model="newExpense" :rules="rules" ref="expenseForm" class="expense-form" label-width="120px">
        <el-form-item label="开销名称" prop="expenseName">
          <el-input v-model="newExpense.expenseName"></el-input>
        </el-form-item>
        <el-form-item label="开销金额" prop="totalAmount">
          <el-input v-model="newExpense.totalAmount" type="number" disabled></el-input>
        </el-form-item>
        <el-form-item label="金额单位" prop="amountUnit">
          <el-radio-group v-model="newExpense.amountUnit">
            <el-radio label="人民币">人民币</el-radio>
            <el-radio label="美元">美元</el-radio>
            <el-radio label="欧元">欧元</el-radio>
            <el-radio label="日元">日元</el-radio>
            <el-radio label="韩元">韩元</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-divider>详细信息</el-divider>
        <div v-for="(detail, index) in newExpense.details" :key="index" class="detail-item">
          <el-form-item label="明细事项" :prop="'details.' + index + '.detailItem'">
            <el-input v-model="detail.detailItem"></el-input>
          </el-form-item>
          <el-form-item label="事项数量" :prop="'details.' + index + '.itemQuantity'">
            <el-input v-model="detail.itemQuantity" type="number" @input="updateTotalPrice(index)"></el-input>
          </el-form-item>
          <el-form-item label="数量单位" :prop="'details.' + index + '.quantityUnit'">
            <el-radio-group v-model="detail.quantityUnit">
              <el-radio label="条">条</el-radio>
              <el-radio label="包">包</el-radio>
              <el-radio label="只">只</el-radio>
              <el-radio label="瓶">瓶</el-radio>
              <el-radio label="台">台</el-radio>
              <el-radio label="张">张</el-radio>
              <el-radio label="把">把</el-radio>
              <el-radio label="本">本</el-radio>
              <el-radio label="辆">辆</el-radio>
              <el-radio label="斤">斤</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="单价" :prop="'details.' + index + '.unitPrice'">
            <el-input v-model="detail.unitPrice" type="number" step="0.01" @input="updateTotalPrice(index)"></el-input>
          </el-form-item>
          <el-form-item label="总价" :prop="'details.' + index + '.totalPrice'">
            <el-input v-model="detail.totalPrice" type="number" step="0.01" disabled></el-input>
          </el-form-item>
          <el-button type="danger" @click="removeDetail(index)" class="remove-detail-button">删除</el-button>
          <el-divider></el-divider>
        </div>
        <el-button type="primary" @click="addDetail" class="add-detail-button">添加明细</el-button>
        <el-form-item>
          <el-button type="primary" @click="validateForm">{{ isEditing ? '更新' : '添加' }}</el-button>
          <el-button @click="resetForm">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog :visible.sync="detailsDialogVisible" title="开销详情" width="50%">
      <el-form :model="detailsExpense" label-width="120px" class="expense-form">
        <el-form-item label="开销名称">
          <el-input :value="detailsExpense.expenseName" disabled></el-input>
        </el-form-item>
        <el-form-item label="开销金额">
          <el-input :value="detailsExpense.totalAmount" disabled></el-input>
        </el-form-item>
        <el-form-item label="金额单位">
          <el-input :value="detailsExpense.amountUnit" disabled></el-input>
        </el-form-item>
        <el-divider>详细信息</el-divider>
        <div v-for="(detail, index) in detailsExpense.details" :key="index">
          <el-form-item label="明细事项">
            <el-input :value="detail.detailItem" disabled></el-input>
          </el-form-item>
          <el-form-item label="事项数量">
            <el-input :value="detail.itemQuantity" disabled></el-input>
          </el-form-item>
          <el-form-item label="数量单位">
            <el-input :value="detail.quantityUnit" disabled></el-input>
          </el-form-item>
          <el-form-item label="单价">
            <el-input :value="detail.unitPrice" disabled></el-input>
          </el-form-item>
          <el-form-item label="总价">
            <el-input :value="detail.totalPrice" disabled></el-input>
          </el-form-item>
          <el-divider></el-divider>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { Message } from 'element-ui';

export default {
  name: 'MajorExpenseManagement',
  data() {
    return {
      expenses: [],
      searchQuery: '',
      newExpense: {
        id: '',
        expenseName: '',
        totalAmount: 0,
        amountUnit: '人民币', // 设置默认值
        details: [],
        createdAt: '',
        updatedAt: ''
      },
      detailsExpense: {
        id: '',
        expenseName: '',
        totalAmount: '',
        amountUnit: '',
        details: [],
        createdAt: '',
        updatedAt: ''
      },
      isEditing: false,
      total: 0,
      page: 1,
      pageSize: 10,
      dialogVisible: false,
      detailsDialogVisible: false,
      rules: {
        expenseName: [{ required: true, message: '请输入开销名称', trigger: 'blur' }],
        totalAmount: [{ required: true, message: '请输入开销金额', trigger: 'blur' }],
        amountUnit: [{ required: true, message: '请选择金额单位', trigger: 'change' }],
        details: {
          type: 'array',
          required: true,
          defaultField: {
            type: 'object',
            fields: {
              detailItem: { required: true, message: '请输入明细事项', trigger: 'blur' },
              itemQuantity: { required: true, message: '请输入事项数量', trigger: 'blur' },
              quantityUnit: { required: true, message: '请选择数量单位', trigger: 'change' },
              unitPrice: { required: true, message: '请输入单价', trigger: 'blur' },
              totalPrice: { required: true, message: '请输入总价', trigger: 'blur' }
            }
          }
        }
      }
    };
  },
  created() {
    this.fetchExpenses();
  },
  methods: {
    fetchExpenses() {
      axios.get('/expenses', {
        params: {
          page: this.page,
          pageSize: this.pageSize,
          expenseName: this.searchQuery
        }
      })
          .then(response => {
            this.expenses = response.data.data.rows;
            this.total = response.data.data.records;
          })
          .catch(error => {
            console.error('Error fetching expenses:', error);
          });
    },
    addExpense() {
      axios.post('/expenses', this.newExpense)
          .then(() => {
            this.fetchExpenses();
            this.resetForm();
            Message.success('添加成功');
          })
          .catch(error => {
            console.error('Error adding expense:', error);
          });
    },
    editExpense(id) {
      axios.get(`/expenses/${id}`)
          .then(response => {
            const expense = response.data.data;
            this.newExpense = {
              ...expense,
              details: Array.isArray(expense.details) ? [...expense.details] : []
            };
            this.isEditing = true;
            this.dialogVisible = true;
          })
          .catch(error => {
            console.error('Error fetching expense details:', error);
          });
    },
    updateExpense() {
      axios.put(`/expenses/${this.newExpense.id}`, this.newExpense)
          .then(() => {
            this.fetchExpenses();
            this.resetForm();
            Message.success('更新成功');
          })
          .catch(error => {
            console.error('Error updating expense:', error);
          });
    },
    deleteExpense(id) {
      axios.delete(`/expenses/${id}`)
          .then(() => {
            this.fetchExpenses();
            Message.success('删除成功');
          })
          .catch(error => {
            console.error('Error deleting expense:', error);
          });
    },
    resetForm() {
      this.newExpense = {
        id: '',
        expenseName: '',
        totalAmount: 0,
        amountUnit: '人民币', // 设置默认值
        details: [],
        createdAt: '',
        updatedAt: ''
      };
      this.isEditing = false;
      this.dialogVisible = false;
    },
    handleDialogClose() {
      this.resetForm();
    },
    openAddDialog() {
      this.resetForm();
      this.isEditing = false;
      this.dialogVisible = true;
    },
    validateForm() {
      this.$refs.expenseForm.validate((valid) => {
        if (valid) {
          this.isEditing ? this.updateExpense() : this.addExpense();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    addDetail() {
      if (!this.newExpense.details) {
        this.$set(this.newExpense, 'details', []);
      }
      this.newExpense.details.push({
        detailItem: '',
        itemQuantity: null, // 设置为 null
        quantityUnit: '条', // 设置默认值
        unitPrice: null, // 设置为 null
        totalPrice: 0
      });
    },
    removeDetail(index) {
      this.newExpense.details.splice(index, 1);
      this.updateTotalAmount();
    },
    updateTotalPrice(index) {
      const detail = this.newExpense.details[index];
      detail.totalPrice = (detail.itemQuantity * detail.unitPrice).toFixed(2);
      this.updateTotalAmount();
    },
    updateTotalAmount() {
      this.newExpense.totalAmount = this.newExpense.details.reduce((sum, detail) => sum + parseFloat(detail.totalPrice || 0), 0).toFixed(2);
    },
    formatDate(row, column, value) {
      if (!value) return '';
      const date = new Date(value);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    },
    showDetails(id) {
      axios.get(`/expenses/${id}`)
          .then(response => {
            const expense = response.data.data;
            this.detailsExpense = {
              ...expense,
              details: Array.isArray(expense.details) ? [...expense.details] : []
            };
            this.detailsDialogVisible = true;
          })
          .catch(error => {
            console.error('Error fetching expense details:', error);
          });
    }
  }
};
</script>

<style scoped>
.major-expense-management {
  height: 100vh;
  overflow: hidden;
  background-image: url('../assets/pdx.png'); /* 确保路径正确 */
  background-size: cover;
  background-position: center;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  padding: 20px;
}

.title {
  color: black;
  margin-top: 20px;
}

.toolbar {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  margin-bottom: 20px;
}

.expense-form {
  width: 100%;
  margin-bottom: 20px;
}

.el-form-item {
  margin-bottom: 10px;
}

.expense-list {
  width: 100%;
}

.detail-item {
  border: 1px solid #ddd;
  padding: 10px;
  margin-bottom: 20px; /* 增加底部的间距 */
  border-radius: 4px;
  background-color: #f9f9f9;
}

.add-detail-button {
  margin-bottom: 20px; /* 添加按钮底部增加间距 */
}
</style>



